package nsq

import (
	"fmt"
	"time"

	"github.com/nsqio/go-nsq"
)

var producer *nsq.Producer

// Init a global producer in memory
func InitProducer(addr string) error {
	if producer != nil {
		return nil
	}
	var err error
	producer, err = nsq.NewProducer(addr, nsq.NewConfig())
	if err != nil {
		return err
	}

	if err := producer.Ping(); err != nil {
		return err
	}

	return nil
}

// Close should be called before the main goroutine exit
// this blocks until completion
func Close() {
	if producer == nil {
		return
	}

	producer.Stop()
}

// Publish synchronously publishes a message body to the specified topic, returning
// an error if publish failed
func Publish(topic string, body []byte) error {
	if producer == nil {
		return fmt.Errorf("producer should be initialed")
	}

	return producer.Publish(topic, body)
}

// DeferredPublish synchronously publishes a message body to the specified topic
// where the message will queue at the channel level until the timeout expires, returning
// an error if publish failed
func DeferredPublish(topic string, delay time.Duration, body []byte) error {
	if producer == nil {
		return fmt.Errorf("producer should be intialed")
	}

	return producer.DeferredPublish(topic, delay, body)
}
